import os
import shutil
import csv
import pandas as pd
# project_dir = os.path.dirname(os.path.abspath(__file__))
# project_dir = os.getcwd()
project_dir = os.path.dirname(os.path.abspath('.'))+'/LSTM/'

def mkdir(path):
    if not os.path.exists(path):
        os.makedirs(path)
    return path


def common_root_path():
    path = project_dir+'/Datas/common/'
    return mkdir(path)


def stk_root_path(code=None):
    path = project_dir+'/Datas/unique/'+code+'/'
    return mkdir(path)


def data_root_path(code=None, is_common=False):
    if is_common:
        return common_root_path()
    else:
        if code:
            return stk_root_path(code=code)
        return None


def data_file_full_path(code=None, is_common=False, fileName=None):
    full_path = data_root_path(code=code, is_common=is_common)
    if fileName!=None:
        return full_path + fileName
    else:
        if is_common:
            return full_path + '/common.csv'
        if code:
            return full_path + code +'.csv'
    return None

def strateg_info_file_full_path(code=None, is_common=False, strategyName='Default',fileName=None):
    if fileName == None:
        raise Exception('输入文件名!!')
    root_path = data_root_path(code=code, is_common=is_common)
    strategy_file_dir = mkdir(root_path+'/'+strategyName+'/')
    return strategy_file_dir+fileName



# 用来判断文件的列结构是否一致
destiontion_csv_coloumns = None
def append_df_to_csv(destination_path=None, data=None, columns=None):
    tmp_data = None
    if isinstance(data, pd.DataFrame):
        tmp_data = data.iloc[-1:, :]
    elif isinstance(data, pd.Series):
        tmp_data = data
    if (not tmp_data.empty) and destination_path:
        has_header = False
        if os.path.exists(destination_path):
            #存在,不写入Header信息
            has_header = True
        with open(destination_path, 'a',encoding='utf-8-sig') as f:
            # 最后一行
            out_put_data_keys = tmp_data.to_dict().keys()
            cs_writer = csv.DictWriter(f, fieldnames=(columns != None) and [x for x in columns if x in out_put_data_keys] or out_put_data_keys)
            if not has_header:
                cs_writer.writeheader()
            cs_writer.writerow(tmp_data.to_dict())
    else:
        pass



def model_root_path(code=None, ktype='D', is_common=False, need_copy=True):
    model_dir_path = data_root_path(code=code, is_common=is_common) + "model-%s/" % ktype
    if os.path.exists(model_dir_path):
        return model_dir_path
    else:
        mkdir(model_dir_path)
        copy_models(destination_dir_path=model_dir_path,destination_model_name=code, is_common=True)
        return model_dir_path

def code_all_datas_path(code=None, is_common=False):
    pass


def check_point_dir(code=None,ktype='D',is_common=False):
    # return './'
    return model_root_path(code=code, ktype=ktype , is_common=is_common)


def copy_models(destination_dir_path, destination_model_name='common', from_code=None, is_common=False):
    data_dir = model_root_path(code=from_code, is_common=is_common)
    # 这里暂时还是直接以common命名
    destination_model_name = 'common'
    if os.path.isdir(data_dir):
        files = os.listdir(data_dir)
        for file_name in files:
            if file_name == 'checkpoint':
                continue
            from_file_full_path = data_dir+file_name
            to_file_full_path = destination_dir_path + file_name
            shutil.copy(from_file_full_path, to_file_full_path)
    if os.path.isdir(destination_dir_path):
        check_point_path = destination_dir_path+'checkpoint'
        f = open(check_point_path, 'w')
        f.write('model_checkpoint_path: "%s%s.model-0"\n' % (destination_dir_path, destination_model_name))
        f.write('all_model_checkpoint_paths: "%s%s.model-0"' % (destination_dir_path, destination_model_name))
        f.close()
    pass

def store_model_file_path(code=None, file_name=None, is_common=False,ktype='D'):
    # return 'stock2.model2'
    if is_common:
        return model_root_path(code=code,ktype=ktype, is_common=is_common)+'common.model'
    else:
        if code:
            return model_root_path(code=code,ktype=ktype, is_common=is_common)+code+'.model'
        return None


# from struct import *
# import numpy as np
# import pandas as pd
# def read_min():
#     ofile = open(project_dir + '/sh000002.lc1','rb')
#     buf = ofile.read()
#     ofile.close()
#     num = len(buf)
#     no = num / 32
#     b = 0
#     e = 32
#     dl = []
#     for i in range(int(no)):
#         a = unpack('hhfffffii', buf[b:e])
#         dl.append([str(int(a[0] / 2048) + 2004) + '-' + str(int(a[0] % 2048 / 100)).zfill(2) + '-' + str(
#             a[0] % 20480).zfill(2), str(int(a[1] / 60)).zfill(2) + ':' + str(a[1] % 60).zfill(2) + ':00', a[2], a[3],
#                    a[4], a[5], a[6], a[7]])
#         b = b + 32
#         e = e + 32
#     df = pd.DataFrame(dl, columns=['date', 'time', 'open', 'high', 'low', 'close', 'amount', 'volume'])
#     pass
#
#
# read_min()
